package cn.northsea.service.impl;


import cn.northsea.listener.LogisticsListener;
import cn.northsea.mapper.*;
import cn.northsea.model.buy.Buy;
import cn.northsea.model.logistics.Logistics;
import cn.northsea.model.material.Material;
import cn.northsea.model.material.Material_detail;
import cn.northsea.model.supplier.Supplier;
import cn.northsea.model.user.UserInfo;
import cn.northsea.model.warehouse.Warehouse;
import cn.northsea.service.LogisticsService;
import cn.northsea.vo.logistics.LogisiticsEeVo;
import cn.northsea.vo.logistics.LogisticsQueryVo;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.yulichang.toolkit.JoinWrappers;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.sun.deploy.net.URLEncoder;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author abc
 * @since 2024-08-21
 */
@Service
public class LogisticsServiceImpl extends ServiceImpl<LogisticsMapper, Logistics> implements LogisticsService {
    @Autowired
    LogisticsListener logisticsListener;

    @Autowired
    LogisticsMapper logisticsMapper;


    @Autowired
    MaterialDetailMapper materialDetailMapper;

    @Autowired
    BuyMapper buyMapper;

    @Autowired
    UsersMapper usersMapper;

    @Autowired
    MaterialMapper materialMapper;

    @Autowired
    SupplierMapper supplierMapper;

    @Autowired
    WarehouseMapper warehouseMapper;


    @Override
    public Map<String, Object> findPage(Page<Logistics> pageParam, LogisticsQueryVo logisticsQueryVo) {
        //获取条件值
        String type = logisticsQueryVo.getType();
        String car_number = logisticsQueryVo.getCarNumber();
        Integer state = logisticsQueryVo.getState();
        //封装条件
        QueryWrapper<Logistics> wrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(type)) {
            wrapper.like("type", type);
        }
        if (!StringUtils.isEmpty(car_number)) {
            wrapper.eq("car_number", car_number);
        }
        if (!StringUtils.isEmpty(state)) {
            wrapper.eq("state", state);
        }
        //调用方法查询
        Page<Logistics> pages = baseMapper.selectPage(pageParam, wrapper);
        long totalCount = pages.getTotal();//总记录数
        long totalPage = pages.getPages();//总页数
        long currentPage = pages.getCurrent();//当前页
        long size = pages.getSize();//每页记录数
        //每页数据集合
        List<Logistics> records = pages.getRecords();
        records.stream().forEach(item -> {
//            this.getTeacherOrSubjectName(item);
        });

        Map<String, Object> map = new HashMap<>();
        map.put("total", totalCount);
        map.put("totalPage", totalPage);
        map.put("records", records);

        System.out.println(records);
        return map;
    }


    //导入
    @Override
    public void importData(MultipartFile file) {
        try {
            EasyExcel.read(file.getInputStream(),
                    LogisiticsEeVo.class, logisticsListener).sheet().doRead();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void updateState(Long id, Integer state) {
        Logistics logistics = new Logistics();
        logistics.setId(id);
        logistics.setState(state);
        baseMapper.updateById(logistics);
    }

    @Override
    public void exportData(HttpServletResponse response) {
        try {
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("物流管理", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            List<Logistics> dictList = baseMapper.selectList(null);
            List<LogisiticsEeVo> dictVoList = new ArrayList<>(dictList.size());
            for (Logistics dict : dictList) {
                LogisiticsEeVo dictVo = new LogisiticsEeVo();
                BeanUtils.copyProperties(dict, dictVo);
                dictVoList.add(dictVo);
            }
            EasyExcel.write(response.getOutputStream(), LogisiticsEeVo.class).sheet("物流管理").doWrite(dictVoList);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    @Override
    public Buy getBuyByLogisticsId(Long id) {
        MPJLambdaWrapper<Logistics> wrapper = JoinWrappers.lambda(Logistics.class)
                .eq(Logistics::getId, id)
                .rightJoin(Buy.class, Buy::getLogisticsId, Logistics::getId)
                .selectAll(Buy.class);
        Buy buy = logisticsMapper.selectJoinOne(Buy.class, wrapper);
        return buy;
    }

    //userId获取Logistics
    @Override
    public List<Logistics> getLogisticsListByUserId(Long userId) {
        MPJLambdaWrapper<Logistics> wrapper = JoinWrappers.lambda(Logistics.class)
                .rightJoin(Buy.class, Buy::getLogisticsId, Logistics::getId)
                .leftJoin(UserInfo.class, UserInfo::getId, Buy::getUserId)
                .eq(UserInfo::getId, userId);
        List<Logistics> logisticsList = logisticsMapper.selectJoinList(Logistics.class, wrapper);
        return logisticsList;
    }


    @Override
    public Material getMaterialByBuyId(Long id) {
        MPJLambdaWrapper<Material> wrapper = JoinWrappers.lambda(Material.class)
                .selectAll()
                .rightJoin(Buy.class, Buy::getMaterialId, Material::getId)
                .eq(Buy::getId, id);
        Material material =materialMapper.selectJoinOne(Material.class, wrapper);
        return material;
    }

    @Override
    public Supplier getSupplierByBuyId(Long id) {
        MPJLambdaWrapper<Supplier> wrapper = JoinWrappers.lambda(Supplier.class)
                .selectAll()
                .rightJoin(Buy.class, Buy::getSupplierId, Supplier::getId)
                .eq(Buy::getId, id);
        Supplier supplier =supplierMapper.selectJoinOne(Supplier.class, wrapper);
        return supplier;
    }


    @Override
    public Material_detail getMaterial_detailByMaterialId(Long id) {
        MPJLambdaWrapper<Material_detail> wrapper = JoinWrappers.lambda(Material_detail.class)
                .selectAll()
                .rightJoin(Material.class, Material::getId, Material_detail::getMaterialId)
                .eq(Material::getId, id);
        Material_detail material_detail =materialDetailMapper.selectJoinOne(Material_detail.class, wrapper);
        return material_detail;
    }

    @Override
    public Warehouse getWarehouseByMaterial_detailId(Long id) {
        MPJLambdaWrapper<Warehouse> wrapper = JoinWrappers.lambda(Warehouse.class)
                .selectAll()
                .rightJoin(Material_detail.class, Material_detail::getWarehourseId, Warehouse::getId)
                .eq(Material_detail::getId, id);
        Warehouse warehouse =warehouseMapper.selectJoinOne(Warehouse.class, wrapper);
        return warehouse;
    }

    @Override
    public UserInfo getUserById(Long id) {
        MPJLambdaWrapper<UserInfo> wrapper = JoinWrappers.lambda(UserInfo.class)
                .selectAll()
                .eq(UserInfo::getId, id);
        UserInfo userInfo =usersMapper.selectJoinOne(UserInfo.class, wrapper);
        return userInfo;
    }


    @Override
    public void addMaterialToWarehouse(Long id, Integer number) {
        Material_detail material_detail = materialDetailMapper.selectById(id);
        material_detail.setNumber(material_detail.getNumber() + number);
        materialDetailMapper.updateById(material_detail);
    }




}
